package com.qfedu.java1234.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.java1234.entity.bo.Menu;
import com.qfedu.java1234.entity.bo.Role;
import com.qfedu.java1234.entity.bo.SysUser;
import com.qfedu.java1234.mapper.MenuMapper;
import com.qfedu.java1234.mapper.RoleMapper;
import com.qfedu.java1234.mapper.UserMapper;
import com.qfedu.java1234.service.UserService;
import com.qfedu.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser>
        implements UserService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    @Override
    public String getUserAuthorityInfo(Long id) {
        StringBuilder authority = new StringBuilder();
        List<Role> roleList = roleMapper.selectList(new QueryWrapper<Role>().inSql("id", "select role_id from sys_user_role where user_id=" + id));
        // 根据用户id获取所有的角色
        if (roleList.size() > 0) {
            String roleCodeStrs = roleList.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
            authority.append(roleCodeStrs);
        }

        // 遍历角色，获取所有菜单权限
        Set<String> menuCodeSet = new HashSet<>();
        for (Role role : roleList) {
            List<Menu> menuList = menuMapper.selectList(new QueryWrapper<Menu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + role.getId()));
            for (Menu menu : menuList) {
                String perms = menu.getPerms();
                if (StringUtil.isNotEmpty(perms)) {
                    menuCodeSet.add(perms);
                }
            }
        }
        if (menuCodeSet.size() > 0) {
            authority.append(",");
            String collect = String.join(",", menuCodeSet);
            authority.append(collect);
        }

        System.out.println("authority = " + authority);
        return authority.toString();
    }
}




